<template>
  <div class="app-container home">
    <!-- 系统概览和实时告警列表放在同一排 -->
    <el-row :gutter="20">
      <!-- 系统概览 - 改为两行布局 -->
      <el-col :sm="24" :lg="6">
        <el-card>
          <div slot="header" class="clearfix">
            <span class="fun-title">电梯火警监测系统</span>
          </div>
          <el-row>
            <el-col :span="24">
              <p>系统概述：本系统为智能化电梯火警监测平台，集成多楼宇实时数据采集、动态分析与预警处理，保障大容量运行安全，实现精准监控与高效响应。</p>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12" style="margin-bottom: 10px;">
              <div class="stat-card">
                <div class="stat-value">{{ totalDevices }}</div>
                <div class="stat-label">设备</div>
              </div>
            </el-col>
            <el-col :span="12" style="margin-bottom: 10px;">
              <div class="stat-card">
                <div class="stat-value">{{ totalChannels }}</div>
                <div class="stat-label">通道</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-card warning" v-if="fireAlarmCount > 0">
                <div class="stat-value">{{ fireAlarmCount }}</div>
                <div class="stat-label">火警报警</div>
              </div>
              <div class="stat-card" v-else>
                <div class="stat-value">0</div>
                <div class="stat-label">火警报警</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-card warning" v-if="deviceAlarmCount > 0">
                <div class="stat-value">{{ deviceAlarmCount }}</div>
                <div class="stat-label">设备报警</div>
              </div>
              <div class="stat-card" v-else>
                <div class="stat-value">0</div>
                <div class="stat-label">设备报警</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 实时告警列表 - 占据更宽空间 -->
      <el-col :sm="24" :lg="18">
        <el-card>
          <div slot="header" class="clearfix">
            <span class="fun-title">实时告警列表</span>
          </div>
          <el-table
            :data="alarmList"
            style="width: 100%"
            size="small"
          >
            <el-table-column prop="type" label="报警类型" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.type === 1" type="danger" size="small">断纤告警</el-tag>
                <el-tag v-else-if="scope.row.type === 2" type="warning" size="small">激光器故障</el-tag>
                <el-tag v-else-if="scope.row.type === 3" type="info" size="small">米标报警</el-tag>
                <el-tag v-else-if="scope.row.type === 4" type="danger" size="small">温度报警</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="time" label="发生时间" width="140"></el-table-column>
            <el-table-column prop="channel" label="通道" width="80"></el-table-column>
            <el-table-column prop="fiberBreakPosition" label="断纤位置" width="100">
              <template slot-scope="scope">
                {{ scope.row.type === 1 ? scope.row.fiberBreakPosition : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="laserTemp" label="激光器温度" width="110">
              <template slot-scope="scope">
                {{ scope.row.type === 2 ? scope.row.laserTemp + '°C' : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="meterMark" label="报警米标" width="100">
              <template slot-scope="scope">
                {{ scope.row.type === 3 ? scope.row.meterMark + '米' : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="meterStatus" label="报警状态" width="100">
              <template slot-scope="scope">
                {{ scope.row.type === 3 ? scope.row.meterStatus : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="alarmTemp" label="报警温度" width="100">
              <template slot-scope="scope">
                {{ scope.row.type === 3 || scope.row.type === 4 ? scope.row.alarmTemp + '°C' : '-' }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 楼栋电梯监测卡片 -->
    <el-divider />
    <div style="margin-bottom: 15px;">
      <span class="fun-title">楼栋电梯状态监测</span>
    </div>
    <el-row :gutter="15">
      <el-col
        v-for="building in buildingData"
        :key="building.id"
        :xs="24"
        :sm="12"
        :md="8"
        :lg="6"
        style="margin-bottom: 15px;"
      >
        <el-card class="building-card" :class="{ 'has-alarm': building.hasAlarm }" shadow="hover" body-style="padding: 12px;">
          <div slot="header" class="clearfix building-header">
            <span class="building-name">{{ building.name }}</span>
            <el-tag
              v-if="building.hasAlarm"
              type="danger"
              size="small"
            >
              告警
            </el-tag>
            <el-tag
              v-else
              type="success"
              size="small"
            >
              正常
            </el-tag>
          </div>

          <!-- 电梯状态列表 - 每行显示两个电梯 -->
          <el-row :gutter="8" class="elevator-list">
            <el-col
              v-for="elevator in building.elevators"
              :key="elevator.id"
              :span="12"
              style="margin-bottom: 8px;"
            >
              <div
                class="elevator-item"
                :class="{
                  'active': activeElevator && activeElevator.id === elevator.id,
                  'warning': elevator.status === 'warning',
                  'danger': elevator.status === 'danger'
                }"
                @click="selectElevator(elevator)"
              >
                <div class="elevator-info">
                  <div class="elevator-name">{{ elevator.name }}</div>
                  <div class="temperature-range">
                    <span>{{ elevator.minTemp }}~{{ elevator.maxTemp }}°C</span>
                    <span v-if="elevator.alarms.length > 0" class="alarm-channels">
                      <el-tooltip
                        v-for="(alarm, index) in elevator.alarms"
                        :key="index"
                        :content="alarm.message"
                        placement="top"
                      >
                        <el-tag type="danger" size="mini" style="margin-left: 3px;">
                          {{ alarm.channel }}
                        </el-tag>
                      </el-tooltip>
                    </span>
                  </div>
                </div>
                <div class="elevator-status">
                  <i
                    class="status-icon"
                    :class="{
                      'el-icon-success': elevator.status === 'normal',
                      'el-icon-warning': elevator.status === 'warning',
                      'el-icon-error': elevator.status === 'danger'
                    }"
                  ></i>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 选中电梯的详细温度信息 -->
    <el-divider v-if="activeElevator" />
    <div v-if="activeElevator" class="elevator-detail">
      <div class="fun-title" style="margin-bottom: 15px;">{{ activeElevator.name }} - 温度监测详情</div>

      <!-- 通道选择和时间粒度选择 -->
      <el-row :gutter="20" style="margin-bottom: 15px;">
        <el-col :span="12">
          <el-radio-group v-model="selectedChannel" size="small">
            <el-radio-button label="all">全部通道</el-radio-button>
            <el-radio-button label="1">通道1</el-radio-button>
            <el-radio-button label="2">通道2</el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col :span="12">
          <el-radio-group v-model="timeRange" size="small" @change="updateTrendChart" style="float: right;">
            <el-radio-button label="minute">分钟</el-radio-button>
            <el-radio-button label="hour">小时</el-radio-button>
            <el-radio-button label="day">日</el-radio-button>
          </el-radio-group>
        </el-col>
      </el-row>

      <!-- 实时温度柱状图和温度趋势图放在同一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card style="margin-bottom: 15px;">
            <div slot="header" class="clearfix">
              <span>实时温度分布 (米标位 1-300)</span>
            </div>
            <div id="realtimeChart" style="height: 250px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div slot="header" class="clearfix">
              <span>温度趋势图</span>
            </div>
            <div id="trendChart" style="height: 250px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
// 引入ECharts
import * as echarts from 'echarts'
import TemperatureMonitor from '@/components/TemperatureMonitor/'

export default {
  name: "Index",
  components: {
    // 局部注册组件
    'temperature-monitor': TemperatureMonitor
  },
  data() {
    return {
      // 版本号
      version: "1.0.0",
      // 图表实例
      charts: {},
      // 选中的电梯
      activeElevator: null,
      // 选中的通道
      selectedChannel: 'all',
      // 时间范围
      timeRange: 'hour',
      // 告警列表
      alarmList: [
        {
          type: 1,
          time: '2023-11-01 10:23:45',
          channel: '1',
          fiberBreakPosition: '45米',
          laserTemp: null,
          meterMark: null,
          meterStatus: null,
          alarmTemp: null
        },
        {
          type: 2,
          time: '2023-11-01 09:15:30',
          channel: '2',
          fiberBreakPosition: null,
          laserTemp: 68,
          meterMark: null,
          meterStatus: null,
          alarmTemp: null
        },
        {
          type: 3,
          time: '2023-11-01 08:42:15',
          channel: '1',
          fiberBreakPosition: null,
          laserTemp: null,
          meterMark: 125,
          meterStatus: '高温',
          alarmTemp: 52
        },
        {
          type: 4,
          time: '2023-11-01 07:30:22',
          channel: '2',
          fiberBreakPosition: null,
          laserTemp: null,
          meterMark: null,
          meterStatus: null,
          alarmTemp: 48
        }
      ],
      // 楼栋数据
      buildingData: [
        {
          id: 1,
          name: '1号楼',
          hasAlarm: true,
          elevators: [
            {
              id: '1-1',
              name: '1#电梯',
              minTemp: 25,
              maxTemp: 38,
              status: 'normal',
              alarms: []
            },
            {
              id: '1-2',
              name: '2#电梯',
              minTemp: 28,
              maxTemp: 52,
              status: 'danger',
              alarms: [
                { channel: '1', position: 3, temperature: 50, message: '1#电梯，1通道，3米标位，温度：50度-超温告警' }
              ]
            },
            {
              id: '1-3',
              name: '3#电梯',
              minTemp: 26,
              maxTemp: 45,
              status: 'warning',
              alarms: [
                { channel: '2', position: 15, temperature: 45, message: '3#电梯，2通道，15米标位，温度：45度-高温预警' }
              ]
            },
            {
              id: '1-4',
              name: '4#电梯',
              minTemp: 24,
              maxTemp: 35,
              status: 'normal',
              alarms: []
            }
          ]
        },
        {
          id: 2,
          name: '2号楼',
          hasAlarm: false,
          elevators: [
            {
              id: '2-1',
              name: '1#电梯',
              minTemp: 23,
              maxTemp: 34,
              status: 'normal',
              alarms: []
            },
            {
              id: '2-2',
              name: '2#电梯',
              minTemp: 24,
              maxTemp: 36,
              status: 'normal',
              alarms: []
            },
            {
              id: '2-3',
              name: '3#电梯',
              minTemp: 25,
              maxTemp: 37,
              status: 'normal',
              alarms: []
            },
            {
              id: '2-4',
              name: '4#电梯',
              minTemp: 23,
              maxTemp: 35,
              status: 'normal',
              alarms: []
            }
          ]
        },
        {
          id: 3,
          name: '3号楼',
          hasAlarm: true,
          elevators: [
            {
              id: '3-1',
              name: '1#电梯',
              minTemp: 26,
              maxTemp: 48,
              status: 'danger',
              alarms: [
                { channel: '1', position: 7, temperature: 48, message: '1#电梯，1通道，7米标位，温度：48度-超温告警' },
                { channel: '2', position: 12, temperature: 46, message: '1#电梯，2通道，12米标位，温度：46度-超温告警' }
              ]
            },
            {
              id: '3-2',
              name: '2#电梯',
              minTemp: 25,
              maxTemp: 39,
              status: 'normal',
              alarms: []
            },
            {
              id: '3-3',
              name: '3#电梯',
              minTemp: 24,
              maxTemp: 36,
              status: 'normal',
              alarms: []
            },
            {
              id: '3-4',
              name: '4#电梯',
              minTemp: 25,
              maxTemp: 42,
              status: 'warning',
              alarms: [
                { channel: '1', position: 25, temperature: 42, message: '4#电梯，1通道，25米标位，温度：42度-高温预警' }
              ]
            }
          ]
        },
        {
          id: 4,
          name: '4号楼',
          hasAlarm: false,
          elevators: [
            {
              id: '4-1',
              name: '1#电梯',
              minTemp: 24,
              maxTemp: 35,
              status: 'normal',
              alarms: []
            },
            {
              id: '4-2',
              name: '2#电梯',
              minTemp: 23,
              maxTemp: 34,
              status: 'normal',
              alarms: []
            },
            {
              id: '4-3',
              name: '3#电梯',
              minTemp: 25,
              maxTemp: 36,
              status: 'normal',
              alarms: []
            },
            {
              id: '4-4',
              name: '4#电梯',
              minTemp: 24,
              maxTemp: 37,
              status: 'normal',
              alarms: []
            }
          ]
        }
      ]
    }
  },
  computed: {
    // 总设备数
    totalDevices() {
      return this.buildingData.reduce((total, building) => {
        return total + building.elevators.length
      }, 0)
    },
    // 总通道数
    totalChannels() {
      return this.totalDevices * 2 // 假设每个设备有2个通道
    },
    // 火警报警数量
    fireAlarmCount() {
      return this.alarmList.filter(alarm => alarm.type === 4).length
    },
    // 设备报警数量
    deviceAlarmCount() {
      return this.alarmList.filter(alarm => alarm.type === 1 || alarm.type === 2).length
    }
  },
  mounted() {
    // 监听窗口大小变化，重新渲染图表
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    // 组件销毁前销毁图表实例和移除事件监听
    Object.values(this.charts).forEach(chart => {
      if (chart) {
        chart.dispose()
      }
    })
    window.removeEventListener('resize', this.handleResize)
  },
  watch: {
    // 监听选中的电梯变化
    activeElevator(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.initRealtimeChart()
          this.initTrendChart()
        })
      }
    },
    // 监听选中的通道变化
    selectedChannel() {
      if (this.activeElevator) {
        this.updateRealtimeChart()
        this.updateTrendChart()
      }
    }
  },
  methods: {
    goTarget(href) {
      window.open(href, "_blank")
    },

    // 选择电梯
    selectElevator(elevator) {
      this.activeElevator = elevator
    },

    // 初始化实时温度柱状图
    initRealtimeChart() {
      const chartDom = document.getElementById('realtimeChart')
      if (!chartDom) return

      this.charts.realtimeChart = echarts.init(chartDom)
      this.updateRealtimeChart()
    },

    // 更新实时温度柱状图
    updateRealtimeChart() {
      if (!this.charts.realtimeChart) return

      // 模拟温度数据 (1-300米标位)
      const positions = Array.from({ length: 300 }, (_, i) => i + 1)
      const temperatures = positions.map(pos => {
        // 模拟温度数据，正常范围25-35度，随机生成
        let baseTemp = 25 + Math.random() * 10
        // 如果有告警位置，设置高温
        if (this.activeElevator.alarms.some(alarm =>
          alarm.position === pos &&
          (this.selectedChannel === 'all' || alarm.channel === this.selectedChannel)
        )) {
          baseTemp = 45 + Math.random() * 10
        }
        return Math.round(baseTemp * 10) / 10
      })

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `位置: ${params[0].name}米<br/>温度: ${params[0].value}°C`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: positions,
          name: '米标位',
          nameLocation: 'middle',
          nameGap: 30
        },
        yAxis: {
          type: 'value',
          name: '温度(°C)',
          min: 20,
          max: 60
        },
        series: [
          {
            name: '温度',
            type: 'bar',
            data: temperatures,
            itemStyle: {
              color: function(params) {
                const value = params.value
                if (value > 45) return '#ff4d4f'
                if (value > 40) return '#faad14'
                return '#52c41a'
              }
            }
          }
        ]
      }

      this.charts.realtimeChart.setOption(option)
    },

    // 初始化温度趋势图
    initTrendChart() {
      const chartDom = document.getElementById('trendChart')
      if (!chartDom) return

      this.charts.trendChart = echarts.init(chartDom)
      this.updateTrendChart()
    },

    // 更新温度趋势图
    updateTrendChart() {
      if (!this.charts.trendChart) return

      // 根据时间范围生成时间数据和温度数据
      let timeData = []
      let tempData1 = [] // 通道1
      let tempData2 = [] // 通道2

      if (this.timeRange === 'minute') {
        // 最近60分钟的数据
        timeData = Array.from({ length: 60 }, (_, i) => {
          const date = new Date()
          date.setMinutes(date.getMinutes() - 59 + i)
          return date.getHours().toString().padStart(2, '0') + ':' + date.getMinutes().toString().padStart(2, '0')
        })
      } else if (this.timeRange === 'hour') {
        // 最近24小时的数据
        timeData = Array.from({ length: 24 }, (_, i) => {
          const date = new Date()
          date.setHours(date.getHours() - 23 + i)
          return date.getHours().toString().padStart(2, '0') + ':00'
        })
      } else {
        // 最近30天的数据
        timeData = Array.from({ length: 30 }, (_, i) => {
          const date = new Date()
          date.setDate(date.getDate() - 29 + i)
          return (date.getMonth() + 1) + '/' + date.getDate()
        })
      }

      // 生成模拟温度数据
      tempData1 = timeData.map(() => {
        let baseTemp = 25 + Math.random() * 15
        // 如果有告警，模拟高温
        if (this.activeElevator.alarms.some(alarm => alarm.channel === '1')) {
          baseTemp = 35 + Math.random() * 20
        }
        return Math.round(baseTemp * 10) / 10
      })

      tempData2 = timeData.map(() => {
        let baseTemp = 25 + Math.random() * 15
        // 如果有告警，模拟高温
        if (this.activeElevator.alarms.some(alarm => alarm.channel === '2')) {
          baseTemp = 35 + Math.random() * 20
        }
        return Math.round(baseTemp * 10) / 10
      })

      const series = []

      if (this.selectedChannel === 'all' || this.selectedChannel === '1') {
        series.push({
          name: '通道1',
          type: 'line',
          data: tempData1,
          smooth: true,
          lineStyle: {
            width: 3
          },
          markLine: {
            data: [
              {
                yAxis: 40,
                name: '预警线',
                lineStyle: {
                  color: '#faad14'
                },
                label: {
                  formatter: '预警线'
                }
              },
              {
                yAxis: 45,
                name: '告警线',
                lineStyle: {
                  color: '#ff4d4f'
                },
                label: {
                  formatter: '告警线'
                }
              }
            ]
          }
        })
      }

      if (this.selectedChannel === 'all' || this.selectedChannel === '2') {
        series.push({
          name: '通道2',
          type: 'line',
          data: tempData2,
          smooth: true,
          lineStyle: {
            width: 3
          },
          markLine: {
            data: [
              {
                yAxis: 40,
                name: '预警线',
                lineStyle: {
                  color: '#faad14'
                },
                label: {
                  formatter: '预警线'
                }
              },
              {
                yAxis: 45,
                name: '告警线',
                lineStyle: {
                  color: '#ff4d4f'
                },
                label: {
                  formatter: '告警线'
                }
              }
            ]
          }
        })
      }

      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: series.map(s => s.name)
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: timeData
        },
        yAxis: {
          type: 'value',
          name: '温度(°C)',
          min: 20,
          max: 65
        },
        series: series
      }

      this.charts.trendChart.setOption(option)
    },

    // 处理窗口大小变化
    handleResize() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.resize()
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }
  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }
  .col-item {
    margin-bottom: 20px;
  }

  .fun-title {
    font-size: 14px;
    font-weight: 500;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }

  // 统计卡片样式
  .stat-card {
    text-align: center;
    padding: 10px 6px;
    background: #f8f9fa;
    border-radius: 6px;
    border-left: 4px solid #1890ff;

    &.warning {
      border-left-color: #faad14;
      background: #fff7e6;
    }

    .stat-value {
      font-size: 18px;
      font-weight: bold;
      color: #1890ff;
      margin-bottom: 3px;
    }

    .stat-label {
      font-size: 11px;
      color: #666;
    }
  }

  // 楼栋卡片样式
  .building-card {
    transition: all 0.3s;

    &.has-alarm {
      border: 1px solid #ff4d4f;
    }

    .building-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;

      .building-name {
        font-size: 14px;
        font-weight: bold;
      }
    }

    .elevator-list {
      .elevator-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 6px;
        border-radius: 4px;
        border: 1px solid #e8e8e8;
        cursor: pointer;
        transition: all 0.3s;
        height: 45px;

        &:hover {
          background: #f5f5f5;
        }

        &.active {
          border-color: #1890ff;
          background: #e6f7ff;
        }

        &.warning {
          border-color: #faad14;
          background: #fff7e6;
        }

        &.danger {
          border-color: #ff4d4f;
          background: #fff1f0;
        }

        .elevator-info {
          flex: 1;

          .elevator-name {
            font-weight: bold;
            margin-bottom: 2px;
            font-size: 12px;
          }

          .temperature-range {
            font-size: 10px;
            color: #666;
            display: flex;
            align-items: center;
            flex-wrap: wrap;

            .alarm-channels {
              margin-left: 3px;
            }
          }
        }

        .elevator-status {
          .status-icon {
            font-size: 14px;

            &.el-icon-success {
              color: #52c41a;
            }

            &.el-icon-warning {
              color: #faad14;
            }

            &.el-icon-error {
              color: #ff4d4f;
            }
          }
        }
      }
    }
  }

  // 电梯详情样式
  .elevator-detail {
    margin-top: 15px;
  }
}
</style>
